package cyz.text.textactivity.core.handler;


public class CyzLooper {
    final CyzMessageQueue mQueue;
    final Thread mThread;
    static final ThreadLocal<CyzLooper> sThreadLocal = new ThreadLocal<>();

    private CyzLooper(boolean quitAllowed) {
        mQueue = new CyzMessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

    public static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new CyzLooper(quitAllowed));
    }

    public static CyzLooper myLooper() {
        return sThreadLocal.get();
    }

    public static void loop() {
        //从全局的一个ThreadLocadMap中获取唯一的Looper对象
        CyzLooper cyzLooper = myLooper();
        //从looper获取到消息队列
        CyzMessageQueue mQueue = cyzLooper.mQueue;
        //写一个死循环
        while (true){
            CyzMessage cyzMessage = mQueue.next();
            if(cyzMessage != null){
                cyzMessage.target.dispatchMessage(cyzMessage);

            }
        }

    }
}
